Java进阶-回顾 HashSet 集合应该掌握什么

  1. 集合对象的创建
  2. 向集合中添加元素
  3. 从集合中取出某个元素
  4. 遍历集合
  5. 测试 HashSet 集合的特点:无序不可重复
  6. HashSet 的 key,存储在 HashMap 集合 key 的元素,需要同时重写 hashCode 和 equals
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetTest {

public static void main(String[] args) {
// 创建集合对象
HashSet<String> set = new HashSet<>();

// 添加元素
set.add("abc");
set.add("def");

// set 集合中的元素不能通过下标取了,没有下标
// 遍历集合(迭代器)
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// 遍历集合(foreach)
for (String s : set) {
System.out.println(s);
}

set.add("vv");
set.add("vv");
set.add("vv");
System.out.println(set.size()); // 3(后面的 vv 没有加进去)

// 创建 Set 集合,存储 Student 数据
Set<Student> students = new HashSet<>();
Student s1 = new Student(1, "zhangsan");
Student s2 = new Student(2, "lisi");
Student s3 = new Student(1, "zhangsan");
students.add(s1);
students.add(s2);
students.add(s3);
System.out.println(students.size()); // 2
for (Student stu : students) {
System.out.println(stu);
}
}
}

class Student {
int no;
String name;

public Student(int no, String name) {
super();
this.no = no;
this.name = name;
}

@Override
public String toString() {
return "Student [no=" + no + ", name=" + name + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + no;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (no != other.no)
return false;
return true;
}
}